/**
 * pipapai: company management 
 * borrowed from settings/js/user.js 
 */

var UserList = {
   useUndo: true,

   /**
    * @brief Initiate user deletion process in UI
    * @param string uid the user ID to be deleted
    *
    * Does not actually delete the user; it sets them for
    * deletion when the current page is unloaded, at which point
    * finishDelete() completes the process. This allows for 'undo'.
    */
   do_delete: function (uid, displayname) {
      if (typeof UserList.deleteUid !== 'undefined') {
         //Already a user in the undo queue
         UserList.finishDelete(null);
      }
      UserList.deleteUid = uid;

      // Set undo flag
      UserList.deleteCanceled = false;

      // Provide user with option to undo
      OC.Notification.showHtml('公司的子帐号<strong>' + escapeHTML(displayname) + '</strong>已删除<span class="undo deleteuser">撤销</span>', 3000);
   },

   /**
    * @brief Delete a user via ajax
    * @param bool ready whether to use ready() upon completion
    *
    * Executes deletion via ajax of user identified by property deleteUid
    * if 'undo' has not been used.  Completes the user deletion procedure
    * and reflects success in UI.
    */
   finishDelete: function (ready) {

      // Check deletion has not been undone
      if (!UserList.deleteCanceled && UserList.deleteUid) {

         // Delete user via ajax
         $.ajax({
            type: 'POST',
            url: OC.filePath('company', 'ajax', 'removesubaccount.php'),
            async: false,
            data: {username: UserList.deleteUid},
            success: function (result) {
               if (result.status == 'success') {
                  // Remove undo option, & remove user from table
                  OC.Notification.hide();
                  $('tr').filterAttr('data-uid', UserList.deleteUid).remove();
                  UserList.deleteCanceled = true;
                  if (ready) {
                     ready();
                  }
               } else {
                  OC.Notification.showHtml(result.data.message+'<span class="undo close">关闭</span>', 3000);
               }
            }
         });
      }
   },

   add: function (username, displayname, groups, sort) {
      $('#subaccountList').show();
      var tr = $('#subaccountList tbody tr').first().clone();
      tr.attr('data-uid', username);
      tr.attr('data-displayname', displayname);
      tr.find('td.username').text(username);
      tr.find('td.displayname').text(displayname);
      var groupsSelect = $('<select multiple="multiple" class="groupsselect" data-placehoder="Groups"></select>').attr('data-uid', username).attr('data-user-groups', groups);
      tr.find('td.groups').empty();
      var allGroups = $('table#subaccountList').attr('data-groups').split(',');
      $.each(allGroups, function (i, group) {
         groupsSelect.append($('<option value="' + escapeHTML(group) + '">' + escapeHTML(group) + '</option>'));
      });
      tr.find('td.groups').append(groupsSelect);
      UserList.applyMultiplySelect(groupsSelect);
      if (tr.find('td.remove img').length == 0) {
         var rm_img = $('<img class="svg action">').attr({
            src: OC.imagePath('core', 'actions/delete')
         });
         var rm_link = $('<a class="action delete">')
            .attr({ href: '#'}).attr('title', '删除')
            .append(rm_img);
         tr.find('td.remove').append(rm_link).read(function() { rm_link.tooltip();});
      }

      var added = false;
      if (sort) {
         displayname = displayname.toLowerCase();
         $('tbody tr').each(function () {
            if (displayname < $(this).attr('data-uid').toLowerCase()) {
               $(tr).insertBefore($(this)).show();
               added = true;
               return false;
            }
         });
      }
      if (!added) {
         $(tr).appendTo('tbody').show();
      }
      return tr;
   },

   applyMultiplySelect: function (element) {
      var checked = [];
      var user = element.attr('data-uid');
      if ($(element).attr('class') == 'groupsselect') {
         if (element.data('user-groups')) {
            checked = String(element.data('user-groups')).split(',');
         }
         if (user) {
            var checkHandeler = function (group) {
               if (checked.length == 1 && checked[0] == group) {
                  return false;
               }
               $.post(
                  OC.filePath('company', 'ajax', 'updatesubaccount.php'),
                  {
                     username: user,
                     group: group
                  },
                  function () {
                  }
               );
            };
         } else {
            checkHandeler = false;
         }
         var addGroup = function (select, group) {
            if(!group || group.length <= 0) return false; 

            var added = false; 
            $('select[multiple]').each(function (index, element) {
               if ($(element).find('option[value="' + group + '"]').length === 0 && select.data('msid') !== $(element).data('msid')) {
                  $(element).append('<option value="' + escapeHTML(group) + '">' + escapeHTML(group) + '</option>');
                  added = true; 
               }
            })
            if(added) {
               var allgroups = $('table#subaccountList').attr('data-groups'); 
               $('table#subaccountList').attr('data-groups', allgroups + "," + escapeHTML(group));
            }
         };

         element.multiSelect({
            createCallback: addGroup,
            createText: "加新分组",
            title: "分组", 
            alwaysFirst: "data-admin", 
            selectedFirst: true,
            checked: checked,
            oncheck: checkHandeler,
            onuncheck: checkHandeler,
            minWidth: 100
         });
      }
   }
};

jQuery.fn.subJobSelect = function(method) {

   var methods = {
      showDialog: function(options)
      {
         var curObj = this; 
         var listurl = options.listurl;
         var btnHtml = '';
         var searchHtml = '';
            
         jQuery.fx.speeds._default = 1000;
         if(options.search) {
            searchHtml = '<div class="searchaction">'+
                             '<span class="medium">搜索：</span>'+
                             '<div class="dialogsearchbg clearfix">'+
                                '<input type="text" value="" class="pull-left search_input"/>'+
                                '<a href="'+options.search.url+'" class="pull-right search_btn"></a>'+
                             '</div>'+
                         '</div>';
         }
         
         if(options.tagselect) {
            searchHtml += '<div class="subacct_postarget"><ul id="jobtagsbox" class="tagbox inputbox"></ul></div>';
         }
         
         if(options.button) {
            btnHtml = '<div class="modal-footer">'+
                          '<a href="javascript:;" class="btn selectall">选择本页所有</a>'+
                          '<a href="javascript:;" class="btn removeselected">清空选择</a>'+
                          '<a href="javascript:;" class="btn btn-info save">确认</a>'+
                      '</div>';
         }
         

         if($("#floatcontainer").length<=0){
        	 jQuery('body').append('<div class="modal hide fade resume_dialogposition" style="position:absolute;" id="floatcontainer">'+
                     '<div class="modal-header">'+
                        '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>'+
                        '<h3>'+options.title+'</h3>'+
                     '</div>'+
                     '<div class="modal-body" id="floatcontainer_body"><div class="dialogp_content">'+searchHtml+'<div id="itemlist"></div></div></div>'+btnHtml+
                  '</div>'); 
         }
         
         
         if(options.tagselect) {
            jQuery(".jobtable td", curObj).each(function() {
               var jobid = jQuery(this).find('input').val();
               var jobtitle = jQuery(this).text();
               if(jobid) {
                  $("<li rvalue='" + jobid + "'>" + jobtitle + "</li>").appendTo(jQuery("#jobtagsbox"));
               }
            });
            
            jQuery("#jobtagsbox").tagit({
               maxNumTags: 0,
               itemName: "job",
               fieldName: "ids",  
               allowUserInput: false,
               onTagRemoved: function(e, tag) {
                  var jobid = tag.find('input').val();
                  jQuery.metadata.setType("attr", "data");
                  jQuery(".joblist td a.cur_a", jQuery('#itemlist')).each(function(){
                     var data = jQuery(this).metadata();
                     if(data.jobid == jobid) {
                        $(this).removeClass('cur_a');
                     }
                  });
               }
            });
         }
       
         var scrolltop = $(window).scrollTop();
         $('#floatcontainer').css({top:scrolltop+50}).modal('show').on('hidden', function() { curObj.subJobSelect("hideDialog");});        
         curObj.subJobSelect("displayJob", options);
      },

      displayJob: function(options)
      {
         var data = {};
         var curObj = this; 
         var listurl = options.listurl;
         var fContainer = jQuery('#floatcontainer');
         var lContainer = jQuery('#itemlist');
         var uid = jQuery('.showlist', curObj).data('uid');
         
         if(options.data) {
            data = options.data;
         }
         
         if(uid) {
            data.uid = uid;
         }
         
         fContainer.off(".subJobSelect");
         lContainer.off();

         lContainer.on("click", "a.selectitem", function(event) {
            curObj.subJobSelect("selectJob", options, jQuery(this)); 
            return false; 
         }).on("click", "a.displaylist", function(event) {
            event.stopPropagation();
            if(!jQuery(this).hasClass("cur_a")) {
               options.listurl = jQuery(this).attr("href"); 
               curObj.subJobSelect("displayJob", options);
            }
            return false; 
         });

         if(options.search) {
            fContainer.on("click.subJobSelect", "a.search_btn", function(event) {
               event.stopPropagation();
               var q = $.trim(jQuery('.search_input', fContainer).focus().val());
               options.listurl = jQuery(this).attr("href").replace('%q', encodeURIComponent(q));
               curObj.subJobSelect("displayJob", options);
               return false; 
            }).on("keydown.subJobSelect", ".search_input", function(event) {
               if(event.which == 13) {
                  event.preventDefault();
                  jQuery('a.search_btn', fContainer).trigger('click');
               }
            });
         }
               
         if(options.tagselect) {
            fContainer.on("click.subJobSelect", "a.selectall", function(event) {
               event.stopPropagation();
               jQuery(".joblist td a", lContainer).not(".cur_a").trigger("click");
               return false;
            }).on("click.subJobSelect", "a.removeselected", function(event) {
               event.stopPropagation();
               jQuery(".joblist td a.cur_a", lContainer).trigger("click");
               return false;
            }).on("click.subJobSelect", "a.save", function(event) {
               var tableHtml = '<tr>';
               var n = jQuery("#jobtagsbox li.tagit-choice").length;                     
               jQuery("#jobtagsbox li.tagit-choice").each(function(i) {
                  var jobid = jQuery(this).find("input").val();
                  var jobtitle = jQuery(this).find(".tagit-label").text();
                        
                  if (i != 0 && (i%3) == 0) {
                     tableHtml += '</tr><tr>';
                  }
                        
                  tableHtml += '<td width="33%">' + jobtitle + '<input type="hidden" name="assignedjobs[]" value="' + jobid + '"></td>';
               });

               filledNum = 3 - (n%3);
               if (filledNum < 3) {
                  for (i=0; i < filledNum; i++) {
                     tableHtml += '<td width="33%"></td>';
                  }
               }
               jQuery(".jobtable", curObj).html(tableHtml);
               if(n > 0) {
                  jQuery(".purposlistbox", curObj).show();
               } else {
                  jQuery(".purposlistbox", curObj).hide();
               }
               curObj.subJobSelect("hideDialog");
            });
         }
               
         jQuery.ajax({
            url: options.listurl,
            data: data,
            cache: false, 
            beforeSend: function(xhr, settings) {
               showLoading(jQuery(".joblist", lContainer));
            },
            success: function(data) {
               lContainer.empty().html(data); 

               if(options.tagselect) {
                  var assigned = jQuery("#jobtagsbox").tagit("assignedTags");
                  jQuery.metadata.setType("attr", "data");
                  jQuery(".joblist td a", lContainer).each(function(){
                     var data = jQuery(this).metadata();
                     if(jQuery.inArray(data.jobid, assigned) != -1) {
                        $(this).addClass('cur_a');
                     }
                  });
               }
               fContainer.show();
            }
         })
      },
      
      selectJob: function(options, target) {
         jQuery.metadata.setType("attr", "data");
         var data = target.metadata();
         if(target.hasClass('cur_a')) {
            if(!jQuery("#jobtagsbox").tagit('removeTagByName', data.jobid)) {
               return false;
            }
            target.removeClass('cur_a');
         } else {
            if(!jQuery("#jobtagsbox").tagit("createTag", data.jobid, null, data.jobtitle)) {
               return false;
            }
            target.addClass('cur_a');
         }
         
      },

      hideDialog: function()
      {
         jQuery("#floatcontainer").modal("hide").remove();
      },

      init: function(options) {
         var curObj = this;
         
         options = jQuery.extend({
            title: '选择职位'
         }, options || {});
         
         /* save a copy so we can reset */      
         options._listurl = options.listurl;
         
         jQuery("body").off(".subJobSelect");
         curObj.off(".subJobSelect");
         
         jQuery("body").on("click.subJobSelect", ".resetsuburl", function(){
            options.listurl = options._listurl;
            curObj.subJobSelect("init", options);
         });
         
         curObj.on("click.subJobSelect", ".showlist", function(){
            curObj.subJobSelect('showDialog', options);
         });
         
      }

   }; 

   if (methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
   } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
   } else {
      $.error( 'Method ' +  method + ' does not exist on subJobSelect' );
   }    
  
};

$(document).ready(function () {
   $("#createuserSpan").click(function(){
      $("#newuserDiv").show();
      $(this).hide();
      $('.resetsuburl').trigger('click');
   });
   
   $(".editaccount_section").on("click", "a.sure", function(){
      $(this).closest("form").ajaxSubmit({
         dataType: "json",
         beforeSubmit: function(data, form, options) {
            var displayname = $("input[name='displayname']", form);
            var displayname_length = compact_strlen(displayname.val());
            if(displayname_length <2 || displayname_length>20){
               showMessagePanel("请输入长度为2~20之间的真实姓名",displayname, true, {placement:"bottom"});
               return false;
            }
            
            var username = $("input[name='username']", form);
            if (!validateEmail($.trim(username.val()))) {
               showMessagePanel("请输入正确的登录邮箱", username, true, {placement:"bottom"});
               return false; 
            }
            
            var password = $("input[name='password']", form);
            if (($.trim(password.val()).length < 6 || $.trim(password.val()).length > 15) && password.is(":visible")) {
               showMessagePanel("请输入长度为6～15之间的合法密码", password, true, {placement:"bottom"});
               return false;
            }
            
            var note = $("input[name='note']", form);
            if (compact_strlen(note.val()) > 16) {
               showMessagePanel("备注长度不能超过32个字符(1个汉字为2个字符）", note, true, {placement:"bottom"});
               return false;
            }
            
            var jobmanage = $("input.jobmanage", form);
            if(jobmanage.is(":checked")) {
               if($(".purview_eachlast input[type=radio]:checked", form).length <= 0) {
                  showMessagePanel("请分配职位", jobmanage, true, {placement:"left"});
                  return false;
               } else if($("input.partjobs", form).is(":checked") && $("table.jobtable td input", form).length <= 0) {
                  showMessagePanel("请分配指定职位", jobmanage, true, {placement:"left"});
                  return false;
               }
            }
            
            if (!showLoading(form, options, null, {button:true}))
               return false;
         },
         success: function(result, status, xhr, form) {
            if (result.status != 'success') {
               $(".server", form).html(result.data.message); 
            } else {
               $(".server", form).html('');
               if(form.attr("id") == "newuser") {
                  form.get(0).reset();
                  $(".assignjobs", form).hide();
                  $(".purview_eachlast", form).addClass("graycolor");
                  $(".purview_eachlast input:radio", form).attr("disabled","disabled");
                  $(".jobtable", form).empty().closest(".purposlistbox").hide();
               }
               $("a.cancel", form).trigger("click");
               
               $.ajax({
                  type: 'GET',
                  url: OC.filePath('company', 'ajax', 'getsubaccountslist.php'),
                  cache: false, 
                  beforeSend: function() {
                     if(!showLoading($("#subaccountList")))
                        return false;
                  },
                  success: function(result){
                     $('#subaccountList').html(result);
                  }
               });
            }
         }
      });
      return false;
   });
   
   $(".editaccount_section").on("click", "a.cancel", function(){
      $(this).closest(".editaccount_section").hide();
      $("#createuserSpan").show();
   });
   
   $(".editaccount_section").on("click", ".purviewcheckbox_second input:checkbox", function(){
      var istrue = $(this).prop("checked");
      var container = $(this).closest(".editaccount_section");
      if(istrue){
         $(".purview_eachlast", container).removeClass("graycolor");
         $(".purview_eachlast input:radio", container).removeAttr("disabled");
         if((".purview_eachlast input.partjobs:radio", container).is(":checked")) {
            $(".purposlistbox", container).show();
         }
         $("em.yellow", container).show();
      }
      else{
         $(".purview_eachlast", container).addClass("graycolor");
         $(".purview_eachlast input:radio", container).attr("disabled","disabled").prop("checked", false);
         $("em.yellow", container).hide();
         $("a.assignjobs", container).hide();
         $(".purposlistbox", container).hide();
      }
   });
   
   $(".editaccount_section").on("click", ".purview_eachlast input:radio", function(){
      var container = $(this).closest(".editaccount_section");
      if($(this).hasClass("alljobs")) {
         $("a.assignjobs", container).hide();
         $(".purposlistbox", container).hide();
      } else {
         if($(".jobtable td", container).length > 0) {
            $(".purposlistbox", container).show();
         } else {
            $("a.assignjobs", container).trigger("click");
         }
         $("a.assignjobs", container).show();
      }
      $(".purviewcheckbox_second input:checkbox", container).val($(this).val());
   });
   
   $(".editaccount_section").on("click", "#changepsswordtext", function(){
      if($(this).hasClass("clicked")) {
         $(this).text("修改密码").removeClass("clicked");
         $("#changepsswordinput").hide().find('input').val('');
      } else {
         $(this).text("不修改密码").addClass("clicked");
         $("#changepsswordinput").show();
      }
   });
   
   $("#newuserDiv").subJobSelect({
      title: '选择职位',
      button: true,
      tagselect: true,
      listurl: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php'),
      search: {url: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php') + '?q=%q'}
   });
   
   $("#edituserDiv").subJobSelect({
      title: '选择职位',
      button: true,
      tagselect: true,
      listurl: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php'),
      search: {url: OC.filePath('company', 'ajax', 'getsubaccountsjoblist.php') + '?q=%q'}
   });
   
   $("#subaccountList").on("click", "a.block_subacct", function(){
      var target = $(this);
      var tr = $(this).closest("tr");
      var uid = tr.attr("data-uid");
      var blockSpan = tr.find("span.notuseacct");
      var block = $(this).hasClass("useornot_subacct") ? 1 : 0;
      
      $.ajax({
         type: "POST",
         url: OC.filePath('company', 'ajax', 'switchsubaccount.php'),
         data: {uid: uid, block: block},
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            if(!$.isPlainObject(result)) {
               result = $.parseJSON(result);
            }
            
            if(result.status === 'success') {
               if(block) {
                  target.removeClass("useornot_subacct").addClass("useornotred_subacct").attr("data-original-title","点击启用");
                  tr.find("td").eq(0).append('<span class="notuseacct">停用</span>');
                  
               } else {
                  target.removeClass("useornotred_subacct").addClass("useornot_subacct").attr("data-original-title","点击停用");
                  blockSpan.remove();
               }
            } else if(result.error) {
               showMessagePanel(result.error, target, true, {placement:'left'});
            }
         }
      });
      
      return false;
   });
   
   $("#subaccountList").on("click", "a.edit_subacct", function(){
      var target = $(this);
      var uid = $(this).closest("tr").attr("data-uid");
      
      $.ajax({
         type: 'GET',
         url: OC.filePath('company', 'ajax', 'getsubaccountsedit.php'),
         data: {uid: uid},
         cache: false, 
         beforeSend: function(xhr, settings) {
            if(!showLoading(target, settings, null, {button:true}))
               return false;
         },
         success: function(result){
            if (!isLoggedIn(result, target)) {
               window.location = redirect_url;
               return;
            }
            
            $("#createuserSpan").hide();
            $('#edituserDiv').html(result).show().siblings(".editaccount_section").hide();
            $('.resetsuburl').trigger('click');
            $(window).scrollTop(0);
         }
      });
      
      return false;
   });
   
   $("#subaccountList").on("click", "a.delete_subacct", function(){
      var target = $(this);
      var tr = $(this).closest("tr");
      var uid = tr.attr("data-uid");
      
      showConfirmDialog('确认删除该子帐号么？',function() {
         $.ajax({
            type: "POST",
            url: OC.filePath('company', 'ajax', 'removesubaccount.php'),
            data: {uid: uid},
            beforeSend: function(xhr, settings) {
               if(!showLoading(target, settings, null, {button:true}))
                  return false;
            },
            success: function(result){
               if (!isLoggedIn(result, target)) {
                  window.location = redirect_url;
                  return;
               }
               
               if(!$.isPlainObject(result)) {
                  result = $.parseJSON(result);
               }
               
               if(result.status === 'success') {
                  tr.hide().nextAll("tr:visible").each(function(){
                     if($(this).hasClass("blue")) {
                        $(this).removeClass("blue");
                     } else {
                        $(this).addClass("blue");
                     }
                  });
               } else if(result.error) {
                  showMessagePanel(result.error, target, true, {placement:'left'});
               }
            }
         });
      });
      
      return false;
   });
});
